package _01_sort.leetcodeexerc.quicksort;

import _01_sort.SortUtil;
import org.junit.Test;

import java.util.Arrays;

import static _01_sort.SortUtil.swap;

/**
 * @author: mornd
 * @dateTime: 2023/6/24 - 16:13
 */
public class QuickSort3 {
    @Test
    public void test() {
        int[] arr = {1, 5, 4, 2, 7, 3, 11};
        sort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }

    private void sort(int[] arr, int left, int right) {
        if (left < right) {
            int p = partition(arr, left, right);
            sort(arr, left, p - 1);
            sort(arr, p + 1, right);
        }
    }

    private int partition(int[] arr, int left, int right) {
        int p = arr[left];
        int i = left + 1;
        int j = right;
        while (i <= j) {
            while (i <= j && arr[i] < p) {
                i++;
            }
            while (i <= j && arr[j] > p) {
                j--;
            }
            if (i <= j) {
                swap(arr, i, j);
                i++;
                j--;
            }
        }
        swap(arr, j, left);
        return j;
    }
}
